import React, { useState, useEffect } from 'react';
import {
    Card,
    Form,
    Input,
    Rate,
    Button,
    Space,
    message,
    Empty,
    Typography
} from 'antd';
import {
    SaveOutlined,
    StarOutlined,
    EditOutlined,
    PlusOutlined,
    ClockCircleOutlined
} from '@ant-design/icons';
import { reviewService } from '../../services/reviewService';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { Text } = Typography;

const ReviewForm = ({ taskId }) => {
    const [form] = Form.useForm();
    const [review, setReview] = useState(null);
    const [loading, setLoading] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [showForm, setShowForm] = useState(true);
    const [currentReviewId, setCurrentReviewId] = useState(null);

    const fetchReview = async () => {
        setLoading(true);
        try {
            const response = await reviewService.getReviewByTask(taskId);
            //console.log('获取到的评价数据:', response);

            // 处理单个评价对象
            const reviewData = response.data.data;
            setReview(reviewData || null);

            // 如果已有评价，隐藏表单，只显示历史评价
            if (reviewData) {
                setCurrentReviewId(reviewData.id);
                setIsEditing(true);
                setShowForm(false); // 隐藏表单，只有点击编辑时才显示

                // 填充表单，为编辑做准备
                form.setFieldsValue({
                    rating: reviewData.rating,
                    comment: reviewData.content
                });
            } else {
                // 没有评价，显示创建表单
                setIsEditing(false);
                setCurrentReviewId(null);
                setShowForm(true);
                form.resetFields();
            }
        } catch (error) {
            message.error('获取评价失败');
            console.error('Error fetching review:', error);
            setReview(null);
            setShowForm(true);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (taskId) {
            fetchReview();
        }
    }, [taskId]);

    const handleSubmit = async (values) => {
        setSubmitLoading(true);
        try {
            // 转换字段名称以匹配后端实体
            const reviewData = {
                content: values.comment,
                rating: values.rating
            };

            console.log('发送到后端的数据:', reviewData);

            if (isEditing && currentReviewId) {
                // 如果是编辑模式，调用更新接口
                await reviewService.updateReview(currentReviewId, reviewData);
                message.success('评价更新成功');
            } else {
                // 如果是新建模式，调用创建接口
                await reviewService.createReview(taskId, reviewData);
                message.success('评价提交成功');
            }

            form.resetFields();
            setShowForm(false);
            fetchReview();
        } catch (error) {
            if (error.response && error.response.data) {
                message.error(error.response.data.message || '提交评价失败');
                console.error('错误详情:', error.response.data);
            } else {
                message.error('提交评价失败');
            }
            console.error('Error handling review:', error);
        } finally {
            setSubmitLoading(false);
        }
    };

    const handleEdit = () => {
        setShowForm(true);
    };

    const handleCancel = () => {
        if (review) {
            // 如果有评价，取消编辑并隐藏表单
            setShowForm(false);
            // 重置表单为当前评价的内容
            form.setFieldsValue({
                rating: review.rating,
                comment: review.content
            });
        } else {
            // 如果没有评价，重置表单
            form.resetFields();
        }
    };

    // 评价展示组件 - 更简洁美观
    const ReviewDisplay = () => {
        if (!review) return null;

        return (
            <div style={{ padding: '8px 0' }}>
                <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <div>
                        <Rate disabled value={review.rating || 0} style={{ fontSize: 18 }} />
                    </div>

                    <div style={{
                        fontSize: 15,
                        lineHeight: '1.8',
                        color: 'rgba(0, 0, 0, 0.85)',
                        whiteSpace: 'pre-wrap'
                    }}>
                        {review.content}
                    </div>

                    <div>
                        <Text type="secondary" style={{ fontSize: 13 }}>
                            <ClockCircleOutlined style={{ marginRight: 5 }} />
                            {review.createdAt ? dayjs(review.createdAt).format('YYYY-MM-DD HH:mm') : '未知时间'}
                        </Text>
                    </div>
                </Space>
            </div>
        );
    };

    return (
        <div>
            <Card
                title={
                    <Space>
                        <StarOutlined />
                        <span>任务评价</span>
                    </Space>
                }
                extra={
                    review && !showForm ? (
                        <Button
                            type="primary"
                            icon={<EditOutlined />}
                            onClick={handleEdit}
                        >
                            编辑评价
                        </Button>
                    ) : null
                }
                loading={loading}
            >
                {showForm ? (
                    <Form
                        form={form}
                        layout="vertical"
                        onFinish={handleSubmit}
                    >
                        <Form.Item
                            name="rating"
                            label="评分"
                            rules={[{ required: true, message: '请选择评分' }]}
                        >
                            <Rate />
                        </Form.Item>

                        <Form.Item
                            name="comment"
                            label="评价内容"
                            rules={[{ required: true, message: '请输入评价内容' }]}
                        >
                            <TextArea
                                rows={4}
                                placeholder="请输入您对此任务的评价..."
                            />
                        </Form.Item>

                        <Form.Item>
                            <Space>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    loading={submitLoading}
                                    icon={isEditing ? <EditOutlined /> : <SaveOutlined />}
                                >
                                    {isEditing ? '更新评价' : '提交评价'}
                                </Button>
                                {review && (
                                    <Button onClick={handleCancel}>
                                        取消
                                    </Button>
                                )}
                            </Space>
                        </Form.Item>
                    </Form>
                ) : (
                    // 只有在不显示表单时才显示评价内容
                    review ? (
                        <ReviewDisplay />
                    ) : (
                        <Empty
                            description="暂无评价"
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                        >
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                onClick={() => setShowForm(true)}
                            >
                                创建评价
                            </Button>
                        </Empty>
                    )
                )}
            </Card>
        </div>
    );
};

export default ReviewForm;
